/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.i18n;

import cn.easyplatform.EasyPlatformRuntimeException;
import cn.easyplatform.contexts.Contexts;
import cn.easyplatform.lang.Streams;
import cn.easyplatform.utils.resource.GResource;
import cn.easyplatform.utils.resource.Scans;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.text.MessageFormat;
import java.util.*;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public final class I18N {

    private final static Logger log = LoggerFactory.getLogger(I18N.class);

    private static Map<String, Properties> resourceMap = new HashMap<String, Properties>();

    private I18N() {
    }

    static {
        try {
            // 加载系统资源文件
            List<GResource> grList = Scans.me().scan("cn/easyplatform/i18n",
                    "^.+[.]properties$");
            for (GResource gr : grList) {
                String fn = FilenameUtils.getBaseName(gr.getName());
                loadResource(fn, gr.getInputStream());
            }
        } catch (Exception ex) {
            throw new EasyPlatformRuntimeException("Fail to load resource", ex);
        }
    }

    public static void loadResource(String name, InputStream is)
            throws IOException {
        String language = "";
        int sp = name.indexOf("_");
        if (sp > 0)
            language = name.substring(sp + 1);
        Properties props = resourceMap.get(language);
        if (props == null) {
            props = new Properties();
            resourceMap.put(language, props);
            if (log.isInfoEnabled())
                log.info("load i18n:{}", language);
        }
        try {
            Reader in = Streams.utf8r(is);
            props.load(in);
            in.close();
            in = null;
        } finally {
            is.close();
        }
    }

    /**
     * @param key
     * @param args
     * @return
     */
    public static String getLabel(String key, Object... args) {
        String locale = null;
        if (Contexts.getCommandContext() != null
                && Contexts.getCommandContext().getUser() != null)
            locale = Contexts.getCommandContext().getUser().getLocale();
        else
            locale = Locale.getDefault().toString();
        Properties rb = resourceMap.get(locale);
        if (rb == null)
            rb = resourceMap.get("zh_CN");
        String temp = rb.getProperty(key);
        if (temp == null) {
            temp = rb.getProperty("easyplatform.message.not.found");
            return MessageFormat.format(temp, key);
        }
        return MessageFormat.format(temp, args);
    }
}
